﻿using log4net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CDV.IRMS.WebAPI.TaskExecution.Filter
{
    /// <summary>
    /// 捕获异常特性
    /// </summary>
    public class HandleExceptionAttribute : ExceptionFilterAttribute
    {
        private readonly ILog _logger = LogManager.GetLogger("TaskExecWebApi", typeof(HandleExceptionAttribute));

        private readonly string _actionDescription;

        private const string ErrorMsgFormatter = "{0}失败，入参：[{1}]，异常信息如下：{2}";

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="actionDescription">Action的描述</param>
        public HandleExceptionAttribute(string actionDescription)
        {
            _actionDescription = actionDescription;
        }

        /// <summary>
        /// 捕获异常
        /// </summary>
        /// <param name="context">异常上下文</param>
        public override void OnException(ExceptionContext context)
        {
            var inputParameter = JsonConvert.SerializeObject(context.ActionDescriptor.Parameters);
            var errorMsg = string.Format(ErrorMsgFormatter, _actionDescription, inputParameter, context.Exception);
            _logger.ErrorFormat(errorMsg);

            context.ExceptionHandled = true;
            context.Result = new JsonResult(new { TaskID = 1, RouteID = 2, ErrorMsg = errorMsg });
        }
    }
}
